﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace System {
    public class ThemeableViewLocationExpander:IViewLocationExpander {
        public const string THEME_KEY = "themename";

        public void PopulateValues(ViewLocationExpanderContext context) {
            var themeContext = (IThemeContext)context.ActionContext.HttpContext.RequestServices.GetService(typeof(IThemeContext));
            context.Values[THEME_KEY] = themeContext.WorkingThemeName;
        }

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,IEnumerable<string> viewLocations) {
            /*
            /Areas/{2}/Views/{1}/{0}.cshtml
            /Areas/{2}/Views/Shared/{0}.cshtml
            /Views/Shared/{0}.cshtml 
            */
            if(context.Values.TryGetValue(THEME_KEY,out string theme)) {
                viewLocations = new[] {
                    $"/Themes/{theme}/Views/{{1}}/{{0}}.cshtml",
                    $"/Themes/{theme}/Views/Shared/{{0}}.cshtml",
                    $"/Themes/{theme}/Areas/{{2}}/Views/{{1}}/{{0}}.cshtml",
                    $"/Themes/{theme}/Areas/{{2}}/Views/Shared/{{0}}.cshtml",
                }.Concat(viewLocations);
            }
            return viewLocations;
        }
    }
    public class ThemeMiddleware {
        private readonly RequestDelegate _next;
        public IConfiguration _configuration;

        public ThemeMiddleware(RequestDelegate next,IConfiguration configuration) {
            _next = next;
            _configuration = configuration;
        }
        public Task Invoke(HttpContext context) {
            var themeContext = (IThemeContext)context.RequestServices.GetService(typeof(IThemeContext));
            context.Request.HttpContext.Items[ThemeableViewLocationExpander.THEME_KEY] = themeContext.WorkingThemeName ?? "Default";
            return _next(context);
        }
    }
}